package Jd;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.IOException;

public class Jd2Add {
    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException, TransformerException {
        DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
        DocumentBuilder db=dbf.newDocumentBuilder();
        Document doc=db.parse("src/Jd/成绩.xml");

        Element studentElement=doc.createElement("student");
        studentElement.setAttribute("id","3");

        Element nameElement=doc.createElement("name");
        nameElement.setAttribute("name","金蝶");

        Element courseElement=doc.createElement("course");
        nameElement.setAttribute("course","英语");

        Element scoreElement=doc.createElement("score");
        nameElement.setAttribute("score","90");

        studentElement.appendChild(nameElement);
        Element scoresElement=(Element) doc.getElementsByTagName("scores").item(0);
        scoresElement.appendChild(studentElement);
        scoresElement.appendChild(courseElement);
        scoresElement.appendChild(scoreElement);

        TransformerFactory transformerFactory=TransformerFactory.newInstance();
        Transformer transform= transformerFactory.newTransformer();
        DOMSource domSource=new DOMSource(doc);

        transform.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
        StreamResult result=new StreamResult(new FileOutputStream("src/Jd/成绩.xml"));
        transform.transform(domSource,result);
    }
}
